# -*- coding: utf-8 -*-

#    OriginDB
#    Copyright (C) 2009  Jason Power <power.jg@gmail.com>
#
#    This program is free software; you can redistribute it and/or modify
#    it under the terms of the GNU General Public License as published by
#    the Free Software Foundation; either version 2 of the License, or
#    (at your option) any later version.
#
#    This program is distributed in the hope that it will be useful,
#    but WITHOUT ANY WARRANTY; without even the implied warranty of
#    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
#    GNU General Public License for more details.
#
#    You should have received a copy of the GNU General Public License along
#    with this program; if not, write to the Free Software Foundation, Inc.,
#    51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.


import sys
sys.path.append('../')

from PyQt4 import QtGui
from PyQt4 import QtCore
from PyQt4 import QtWebKit

from mainWindow import MainWindow
from compoundEdit  import CompoundEdit
from reactionEdit  import ReactionEdit
from referenceEdit import ReferenceEdit
from searchResults import SearchResults
from login import LoginDialog, PasswordDialog
from catalystEdit import CatalystEdit
from pubchemImport import PubChemImport
import errorHandler

import database
import molsketch

try:
	import visual
except ImportError:
	visual = None

class Controller:

	def __init__(self, app):

		self.app = app

		self.dialog = None

		self.compoundEditFrame = CompoundEdit(self, database.Compound, "Search")

		self.reactionEditFrame = ReactionEdit(self, database.Reaction, database.Relation, database.Catalyst)
		self.referenceEditFrame = ReferenceEdit(self, database.Reference)
		self.searchResultsFrame = SearchResults(self)

		self.mainWindow = MainWindow(self)

		self.mainWindow.addEditFrames(self.compoundEditFrame, self.reactionEditFrame, self.referenceEditFrame)

		self.mainWindow.setEditFrame(self.compoundEditFrame)
		self.mainWindow.setSearchFrame(self.searchResultsFrame)


	def go(self):
		self.mainWindow.show()
		self.loginAction(None)
		database.dbHandle.setErrorHandler(errorHandler.myerrorhandler)

	def newCompoundAction(self):
		self.compoundEditFrame.clear()
		self.compoundEditFrame.setMode("New")
		self.setEditFrame(self.compoundEditFrame)

	def searchCompoundAction(self):
		self.compoundEditFrame.clear()
		self.compoundEditFrame.setMode("Search")
		self.setEditFrame(self.compoundEditFrame)

	def searchCompoundDialog(self, mode):
		self.searchResultsFrame.clear()

		if mode == "Reactant":
			self.searchResultsFrame.setMode("Adding Reactant")
		if mode == "Product":
			self.searchResultsFrame.setMode("Adding Product")

		self.dialog = QtGui.QDialog(self.mainWindow)
		self.dialog.frame = CompoundEdit(self, database.Compound, "Dialog")
		self.dialog.frame.setParent(self.dialog)
		self.dialog.frame.show()
		self.dialog.setModal(True)
		self.dialog.show()

	def catalystDialog(self, mode):
		self.dialog = QtGui.QDialog(self.mainWindow)
		self.dialog.frame = CatalystEdit(self, database.Catalyst, mode)
		self.dialog.frame.setParent(self.dialog)
		self.dialog.frame.show()
		self.dialog.setModal(True)
		self.dialog.show()

	def referenceDialog(self, mode):
		self.searchResultsFrame.clear()
		self.searchResultsFrame.setMode("Adding Reference")

		self.dialog = QtGui.QDialog(self.mainWindow)
		self.dialog.frame = ReferenceEdit(self, database.Reference, mode+" Dialog")
		self.dialog.frame.setParent(self.dialog)
		self.dialog.frame.show()
		self.dialog.setModal(True)
		self.dialog.show()

	def newReactionAction(self):
		self.reactionEditFrame.clear()
		self.reactionEditFrame.setMode("Adding")
		self.setEditFrame(self.reactionEditFrame)

	def newReferenceAction(self):
		self.referenceEditFrame.clear()
		self.referenceEditFrame.setMode("New")
		self.setEditFrame(self.referenceEditFrame)

	def searchReferenceAction(self):
		self.referenceEditFrame.clear()
		self.referenceEditFrame.setMode("Search")
		self.setEditFrame(self.referenceEditFrame)

	def informationAction(self):
		self.mainWindow.viewEditFrame()

	def viewSearchAction(self):
		self.mainWindow.viewSearchFrame()

	def detailsAction(self):
		self.mainWindow.viewDetailsFrame()

	def setEditFrame(self, frame):
		self.mainWindow.setEditFrame(frame)

	def molsketchCallback(self, molfile):
		if molfile:
			self.compoundEditFrame.setStructure(molfile)

	def viewStructure(self):
		molfile = self.compoundEditFrame.getStructureText()
		if molfile:
			molsketch.run(self.molsketchCallback, str(molfile))
		else:
			molsketch.run(self.molsketchCallback)

	def createCompound(self, name, formula, iupac, inchi, structure):
		compound = database.Compound()

	def searchCompound(self, compound):
		compounds = database.searchForCompound(compound)
		self.searchResultsFrame.clear()
		self.searchResultsFrame.setMode("Compound")
		if len(compounds) == 0:
			self.displayNoneFound()
			return
		self.addCompoundsToSearch(compounds)

	def searchCompoundFromDialog(self, compound):
		compounds = database.searchForCompound(compound)
		if self.dialog:
			self.dialog.close()
		if len(compounds) == 0:
			self.displayNoneFound()
			return
		self.addCompoundsToSearch(compounds)

	def addCompoundsToSearch(self, compounds, message=""):
		if message:
			self.searchResultsFrame.clear()
			self.searchResultsFrame.setMode(message)
		self.searchResultsFrame.addCompounds(compounds)

	def searchProducts(self, compound):
		self.searchResultsFrame.clear()
		self.searchResultsFrame.setMode("Products of "+compound.name)
		relations = database.searchForProducts(compound)
		self.searchResultsFrame.addRelations(relations)

	def searchReactants(self, compound):
		self.searchResultsFrame.clear()
		self.searchResultsFrame.setMode("Reactants that produce "+compound.name)
		relations = database.searchForReactants(compound)
		self.searchResultsFrame.addRelations(relations)

	def searchReference(self, reference):
		references = database.searchForReference(reference)

		self.searchResultsFrame.clear()
		self.searchResultsFrame.setMode("Reference")
		if len(references) == 0:
			self.displayNoneFound()
			return
		self.searchResultsFrame.addReferences(references)

	def searchReferenceFromDialog(self, reference):
		references = database.searchForReference(reference)
		if self.dialog:
			self.dialog.close()
		if len(references) == 0:
			self.displayNoneFound()
			return
		self.searchResultsFrame.addReferences(references)

	def searchCatalyst(self, catalyst):
		self.searchResultsFrame.clear()
		self.searchResultsFrame.setMode("Adding Catalyst")

		catalysts = database.searchForCatalyst(catalyst)
		if self.dialog:
			self.dialog.close()
		if len(catalysts) == 0:
			self.displayNoneFound()
			return
		self.searchResultsFrame.addCatalysts(catalysts)

	def setViewCurrentCompound(self, compound):
		self.compoundEditFrame.clear()
		self.compoundEditFrame.setCurrentCompound(compound)

	def setViewCurrentReference(self, reference):
		self.referenceEditFrame.clear()
		self.referenceEditFrame.setCurrentReference(reference)

	def setViewCurrentReaction(self, reaction):
		self.setEditFrame(self.reactionEditFrame)
		self.reactionEditFrame.setMode("Update")
		self.reactionEditFrame.clear()
		self.reactionEditFrame.setCurrentReaction(reaction)

	def addToReaction(self, obj, where):
		if self.dialog:
			self.dialog.close()
		self.reactionEditFrame.addToList(obj, where)

	def loginAction(self, checked):
		self.login = LoginDialog(self)
		self.login.setModal(True)
		self.login.show()

	def logoutAction(self, checked):
		database.userUtils.logout()
		self.setReadonly()
		self.msgDialog = QtGui.QMessageBox(QtGui.QMessageBox.Information, "Logged Out", "Successfully logged out", QtGui.QMessageBox.Ok)
		self.msgDialog.setModal(True)
		self.msgDialog.show()

	def passwordAction(self, checked):
		self.passDialog = PasswordDialog()
		self.passDialog.setModal(True)
		self.passDialog.show()

	def importCompoundAction(self):
		self.compoundEditFrame.setMode("New")
		self.setEditFrame(self.compoundEditFrame)
		self.dialog = PubChemImport(self, database.Compound)
		self.dialog.setModal(True)
		self.dialog.show()

	def importReferenceAction(self):
		self.referenceEditFrame.setMode("New")
		self.setEditFrame(self.referenceEditFrame)
		self.referenceEditFrame.importReference()

	def userLoggedIn(self):
		return database.userUtils.userLoggedIn()

	def setReadonly(self):
		self.compoundEditFrame.setReadonly(not self.userLoggedIn())
		self.referenceEditFrame.setReadonly(not self.userLoggedIn())
		self.reactionEditFrame.setReadonly(not self.userLoggedIn())

	def displayNoneFound(self):
		self.msgDialog = QtGui.QMessageBox(QtGui.QMessageBox.Information, "No Items Found", "The search returned zero results", QtGui.QMessageBox.Ok)
		self.msgDialog.setModal(True)
		self.msgDialog.show()
		
	def viewVisualization(self):
		self.visualDialog = visual.VisualWindow(self)
		self.visualDialog.show()
